package com.jbp.service.impl;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jbp.dao.InviteRewardDao;
import com.jbp.model.InviteReward;
import com.jbp.model.User;
import com.jbp.model.Wallet;
import com.jbp.model.WalletRecord;
import com.jbp.service.*;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jbp.utils.PageUtils;
import com.jbp.utils.Query;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 推广奖励(InviteReward)表服务实现类
 * @author cc
 * @since 2020-07-26 13:53:10
 */
@Service
public class InviteRewardServiceImpl extends ServiceImpl<InviteRewardDao, InviteReward> implements InviteRewardService {

    @Autowired
    private UserService userService;

    @Autowired
    private WalletService walletService;

    @Autowired
    private WalletRecordService walletRecordService;
    @Autowired
    private UserLevelService userLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<InviteReward> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("user_id", "provide_user_id", "sum(amount) as total");
        queryWrapper.eq("user_id", params.get("userId"));
        queryWrapper.groupBy("provide_user_id");
        queryWrapper.orderByDesc("total");

        IPage<InviteReward> page = this.page(
                new Query<InviteReward>().getPage(params),
                queryWrapper
        );

        page.getRecords().forEach(inviteReward -> {
            User provider = userService.getById(inviteReward.getProvideUserId());
            inviteReward.setProvideUserName(provider.getName());
            inviteReward.setProvideUserImg(provider.getImg());
            inviteReward.setProvideUserSex(provider.getSex());
            inviteReward.setProvideUserLevel(provider.getLevel());
            inviteReward.setProvideUserLevelOn(userLevelService.levelOn(provider.getId()));
        });

        return new PageUtils(page);
    }

    @Override
    public Map<String, Object> info(Integer userId) {

        //已发奖励
        BigDecimal yfjl = getBaseMapper().yfjl(userId);
        if(yfjl==null) {
            yfjl = BigDecimal.ZERO;
        }
        //待发奖励
        BigDecimal dfjl = getBaseMapper().dfjl(userId);
        if(dfjl==null) {
            dfjl = BigDecimal.ZERO;
        }
        //被邀请奖励
        BigDecimal byqjl = getBaseMapper().byqjl(userId);
        if(byqjl==null) {
            byqjl = BigDecimal.ZERO;
        }
        //邀请码
        String inviteCode = userService.getById(userId).getCode();

        HashMap<String, Object> map = new HashMap<>();
        map.put("yfjl", yfjl); //已发奖励
        map.put("dfjl", dfjl); //待发奖励
        map.put("byqjl", byqjl);//被邀请奖励
        map.put("inviteCode", inviteCode);//邀请码
        return map;
    }

    /**提取待发奖励*/
    @Override
    @Transactional
    public synchronized void extract(Integer userId) {
        QueryWrapper<InviteReward> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("status", "create");
        List<InviteReward> list = list(queryWrapper);

        if (list==null || list.size()==0) {
            return;
        }

        //奖励金额汇总
        BigDecimal reward = BigDecimal.ZERO;
        for (InviteReward inviteReward : list) {
            reward = reward.add(inviteReward.getAmount());
            inviteReward.setStatus("success");
        }
        //修改奖励状态
        updateBatchById(list);

        //发放奖励
        Wallet myWallet = walletService.getByUserId(userId);
        WalletRecord myWalletRecord = new WalletRecord();
        myWalletRecord.setUserId(userId);
        myWalletRecord.setOperationType("invite");
        myWalletRecord.setCoinType("xinzuan");
        myWalletRecord.setAddType("add");
        myWalletRecord.setBeforeBalance(myWallet.getXinzuan());
        myWalletRecord.setChangeBalance(reward);
        myWalletRecord.setAfterBalance(myWallet.getXinzuan().add(reward));
        walletRecordService.save(myWalletRecord);

        myWallet.setXinzuan(myWallet.getXinzuan().add(reward));
        walletService.updateWithLock(myWallet);
    }
}